package com.youfan.consumer;

import com.rabbitmq.client.Channel;
import com.youfan.config.RabbitMsgConvertConfigure;
import com.youfan.entity.YoufanOrder;
import com.youfan.re.Result;
import com.youfan.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消费订单
 */
@Component
// @RabbitListener除了可以作用在方法，也可以作用在类上。在后者的情况下，需要在处理的方法使用@RabbitHandler。一个类可以配置多个@RabbitHandler
@RabbitListener(queues = RabbitMsgConvertConfigure.SPRING_BOOT_QUEUE)
public class ReceiveYoufanOrder {
    Logger logger= LoggerFactory.getLogger(ReceiveYoufanOrder.class);

    @Autowired
    private OrderService orderService;


    @RabbitHandler
    public void receiveYoufanOrder(YoufanOrder youfanOrder, Channel channel, Message message) {
        // ...
        try {
            logger.info("[ReceiveYoufanOrder-YoufanOrder] receive receiveYoufanOrder msg: " + youfanOrder);
            // 幂等性 todo
            Result<Integer>  result =  orderService.add(youfanOrder);
            int numers = result.getData();
            if(numers<1) throw new Exception("调用订单服务 存储失败");
            //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }


    }

    @RabbitHandler
    public void receiveYoufanOrderString(String youfanOrder) {
        // ...
        try {
            logger.info("[ReceiveYoufanOrder-YoufanOrder] receive receiveYoufanOrderString msg: " + youfanOrder);
            // 幂等性 todo
//            Result<Integer>  result =  orderService.add(youfanOrder);
//            int numers = result.getData();
//            if(numers<1) throw new Exception("调用订单服务 存储失败");
            //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
//            try {
////                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);
//            } catch (IOException e1) {
//                e1.printStackTrace();
//            }
            e.printStackTrace();
        }


    }

    @RabbitHandler
    public void receiveYoufanOrderString(byte pyte[]) {
        logger.info("[ReceiveYoufanOrder-YoufanOrder] receive receiveYoufanOrderString msg: "+new String(pyte));
    }
}